
/*
 * Karvaly.DOM.Event
 * depends: Karvaly.DOM, Karvaly.Class
 */
Karvaly.DOM.Event = (function(window) {
    
    var Class = Karvaly.Class;
    
    var Event = new Class({
	constructor : function(event) {
	    this.initEvent(event);
	},
	initEvent : function(event) {
	    if (!event)	return;
	    this.current = event;
	    this.type = event.type;
	    this.target = event.target || event.srcElement;
	},
	preventDefault : function() {
	    var event = this.current;
	    if (event) {
		if (event.preventDefault) event.preventDefault();
		else event.returnValue = false;
	    }
	},
	stopPropagation : function() {
	    var event = this.current;
	    if (event) {
		if (event.stopPropagation) event.stopPropagation();
		else event.cancelBuble = true;
	    }
	}
    });

    Event.addListener = function(node, type, callback) {
	var listener;
	if (Event.listeners.indexOf(node, type, callback) !== -1) return;
	listener = function(event) {
	    callback.call(node, event || window.event);
	};
	try {
	    node.addEventListener(type, listener, false);
	} catch (e) {
	    node.attachEvent('on' + type, listener);
	}
	Event.listeners.push({
	    node : node,
	    type : type,
	    callback : callback,
	    listener : listener
	});
    };
    
    Event.listeners = [];
    
    Event.listeners.indexOf = function(node, type, callback) {
	var i, listener;
	for (i = 0; i < Event.listeners.length; i++) {
	    listener = Event.listeners[i];
	    if (listener.node === node && listener.type === type && listener.callback === callback) return i;
	}
	return -1;
    };

    Event.removeEvent = function(node, type, callback) {
	var index = Event.listeners.indexOf(node, type, callback), listener;
	if (index === -1) return;
	listener = Event.listeners[index].listener;
	try {
	    node.removeEventListener(type, listener, false);
	} catch (e) {
	    node.detachEvent('on' + type, listener);
	}
	Event.listeners.splice(index, 1);	
    };
    
    return Event;    
})(this);
